package com.streambolics.appengine;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.streambolics.data.PersistentObject;
import com.streambolics.servlet.ClientAwareServlet;
import com.streambolics.std.TimeZoneUtil;

/**
 * A Servlet that connects to the Google Engine Persistence manager.
 * 
 * @author Sauron
 * 
 */

public abstract class PersistenceAwareServlet<T> extends ClientAwareServlet<T>
{
    /**
     * 
     */
    private static final long                      serialVersionUID    = 1L;
    private static final PersistenceManagerFactory _PersistenceFactory = JDOHelper.getPersistenceManagerFactory ("transactions-optional");
    private PersistenceManager                     _Database;

    protected String getCountryCode ()
    {
        return getHeader ("x-AppEngine-country");
    }

    /**
     * The currently connected database connection.
     * 
     * @return The persistence manager to use for database connection.
     */

    protected PersistenceManager getDatabase ()
    {
        return _Database;
    }

    protected String getTimeZoneName ()
    {
        return TimeZoneUtil.countryCodeToTimeZoneName (getCountryCode ());
    }

    protected void save (PersistentObject o)
    {
        _Database.makePersistent (o);
    }

    @Override
    protected void setupEnvironment (HttpServletRequest aRequest, HttpServletResponse aResponse) throws Exception
    {
        super.setupEnvironment (aRequest, aResponse);
        _Database = _PersistenceFactory.getPersistenceManager ();
    }

    @Override
    protected void teardownEnvironment () throws Exception
    {
        try
        {
            _Database.close ();
        }
        finally
        {
            super.teardownEnvironment ();
        }
    }
}
